<?php
class Viewer {
	/**
	 * 获取smarty对象
	 * @param $template_dir 模板路径
	 */
	public static function get_view(){
		global $view_service_pool;
		if($view_service_pool == null){
			$view_service = Viewer::get_view_entity();
			$view_service_pool[] = $view_service;
			return $view_service;
		}
		
		foreach ($view_service_pool as &$temp_view_service){
			if($temp_view_service->is_free){
				return $temp_view_service;
			}
		}
		$view_service = Viewer::get_view_entity();
		$view_service_pool[] = $view_service;
		return $view_service;
	}
	
	/**
	 * 实例化一个Smarty对象，并初始化
	 * @throws Exception
	 */
	private static function get_view_entity(){
		//获取Smarty
		include_once ROOT_PATH.'/protected/includes/smarty/Smarty.class.php';
		$view_service = new YuSmarty;
		$view_service->left_delimiter = SMARTY_LEFT_DELIMITER;
		$view_service->right_delimiter = SMARTY_RIGHT_DELIMITER;
		$view_service->cache_dir =  ROOT_PATH . '/protected/temp/cached';
		$view_service->compile_dir = ROOT_PATH . '/protected/temp/compiled';
		//注册自定义标签
		$template_tags_dir = ROOT_PATH.'/protected/includes/smarty/userplugins/';
		if(is_dir($template_tags_dir)){
			$handle = opendir($template_tags_dir); 
			while (false !== ($file = readdir($handle))){
				if(strstr($file, '.php')){
					//只读取PHP目录
					$self_tag_name = null;
					$smarty_plus_type = Smarty::PLUGIN_FUNCTION;
					$function_name = preg_replace('/^(.*)\.php$/i', '$1', $file);
					require_once $template_tags_dir . $file;
					if(!empty($self_tag_name)){
						if (isset($view_service->registered_plugins[$smarty_plus_type][$self_tag_name])) {
							throw new Exception("Plugin tag '{$self_tag_name}' already registered");
						}
						//注册标签
						$view_service->registerPlugin($smarty_plus_type, $self_tag_name, $function_name);
					}
				}
			}
		}
		$view_service->is_free = false;
		return $view_service;
	}
}

?>